<?php

namespace App\Api\Controllers;

use App\Models\Class_section_group;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use DB;

class GetGroupController extends Controller
{
    public function get_group(Request $request)
    {
        // $sectionId = $request->get('q');
        // $list = Class_section_group::where(['pid' => $sectionId, 'type' => 2])->get(['id', DB::raw('name as text')]);
        // foreach ($list as $key => $value) {
        //     $arr[] = array("id" => $value->id, "text" => $value->text);
        // }
        // return $arr;//返回数组到分组的option

        $sectionId = $request->get('q');
        return Class_section_group::where('pid','=', $sectionId)->get(['id', DB::raw('name as text')]);
    }

    public function get_group_user(Request $request)
    {
        // $sectionId = $request->get('q');
        // $list = Class_section_group::where(['pid' => $sectionId, 'type' => 2])->get(['id', DB::raw('name as text')]);
        // foreach ($list as $key => $value) {
        //     $arr[] = array("id" => $value->id, "text" => $value->text);
        // }
        // return $arr;//返回数组到分组的option

        $sectionId = $request->get('q');
        $user = $request->get('user');
        if($sectionId == 0){
            $arr = Class_section_group::where('pid','>', 0)->get(['id', DB::raw('name as text')]);
            $data = array();
            $data[] = array('id'=>0,'text'=>'全部');
            foreach($arr as $v){
                $data[]=array('id'=>$v->id,'text'=>$v->text);
            }
            return $data;
        }
        $num = DB::table('class_section_groups')->where('id','=',$sectionId)->whereRaw('find_in_set('.$user.',`charge`)')->count();
        if($num > 0){
            //班段负责人直接返回下面所有分组
            $arr = Class_section_group::where('pid','=', $sectionId)->get(['id', DB::raw('name as text')])->toArray();
            array_unshift($arr,['id'=>0,'text'=>'全部']);
            return $arr;
        }else{
            //返回所有负责的分组和 所带班所在的分组
            $class = DB::table('squads')->where('class_teacher','=',$user)->select(DB::raw('distinct(`group`) as group_id'))->get();
            $class_arr = array();
            foreach($class as $v){
                $class_arr[] = $v->group_id;
            }
            $arr = Class_section_group::where('pid','=', $sectionId)->where(function($query) use ($user,$class_arr){
                $query->whereIn('id',$class_arr);
                $query->orWhereRaw('find_in_set('.$user.',`charge`)');
            })->get(['id', DB::raw('name as text')])->toArray();
            array_unshift($arr,['id'=>0,'text'=>'全部']);
            return $arr;
        }
    }
}
